package org.dtrd.common.exception;

import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.Validator;
import java.nio.charset.StandardCharsets;

/**
 * @author xiao
 * @date 2022/6/21 10:10 AM
 */
@Configuration
public class ValidationConfig {

    @Bean
    public MessageSource messageSource(){
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
        messageSource.setCacheMillis(-1);
        messageSource.setBasename("ValidationMessages");
        return messageSource;
    }

    @Bean
    public Validator validator(){
        LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
        MessageInterpolatorFactory interpolatorFactory  = new MessageInterpolatorFactory();
        factory.setMessageInterpolator(interpolatorFactory.getObject());
        factory.setValidationMessageSource(messageSource());
        return factory;
    }

}
